class Manage::PostsController < Manage::MainController
  before_filter :find_structure
  before_filter :find_post, :only=>[:edit, :update, :destroy]
  before_filter :update_params, :only=>[:create, :update]
  
  cache_sweeper :post_sweeper, :only=>[:create, :update, :destroy]
  
  # GET /manage/structures/1/posts
  # GET /manage/structures/1/posts.xml
  def index
    @posts = @structure.posts.paginate(:all, :page=>params[:page], :per_page=>20, :order=>"created_at DESC")
    
    respond_to do |format|
      format.html # render index.html
      format.xml{ render :xml => @posts }
    end
  end
  
  # GET /manage/structures/1/posts/new
  def new
    @post = @structure.posts.new :language=>I18n.locale
    @post.user = current_user
  end
  
  # POST /manage/structures/1/posts
  # POST /manage/structures/1/posts.xml
  def create
    @post = @structure.posts.new(params[:post])
    @post.user = @user
    
    respond_to do |format|
    	if @post.valid? && @post.save
        flash[:notice] = I18n.t('flash.post.created')
        
        format.html { redirect_to manage_structure_posts_path(@structure.id) }
        format.xml { head :ok }
      else
      	flash.now[:error] = I18n.t('flash.post.create_error')
      	
        format.html { render :action => "new" }
        format.xml { render :xml => @post.errors, :status => :unprocessable_entity }
      end
    end
  end
  
  # PUT /manage/structures/1/posts/1
  # PUT /manage/structures/1/posts/1.xml
  def update
    @post.user = @user
        
    respond_to do |format|
    	if @post.update_attributes(params[:post])
        flash[:notice] = I18n.t('flash.post.updated')
        
        format.html { redirect_to manage_structure_posts_path(@structure.id) }
        format.xml { head :ok }
      else
      	flash.now[:error] = I18n.t('flash.post.update_error')
      	
        format.html { render :action => "edit" }
        format.xml { render :xml => @post.errors, :status => :unprocessable_entity }
      end
    end
  end
  
  # DELETE /manage/structures/1/posts/1
  # DELETE /manage/structures/1/posts/1.xml
  def destroy
    @post.destroy
    flash[:notice] = I18n.t('flash.post.destroy')
    
    respond_to do |format|
      format.html { redirect_to manage_structure_posts_path(@structure.id) }
      format.xml { head :ok }
    end
  end
  
  private
  
  def update_params
    @user = current_user
  end
  
  def find_post
    @post = @structure.posts.find(params[:id])
  end
  
  def find_structure
    @structure = Structure.find(params[:structure_id])
  end
end
